<template>
	<view class="page">
		<cu-custom bgColor="bg-white" :isBack="true"><block slot="content"></block></cu-custom>
		<canvas canvas-id="myCanvas" :style="canvasStyle"></canvas>
		<view class='whiteContent'>
		  <image v-if="tempSavedImageURL" :src='tempSavedImageURL' mode='aspectFit' style='height:100%;width:100%'></image>
		</view>
		<view class='margin-top-sm bg-white flex-1' style="position: fixed;bottom:0;width: 100%;">
			<view class='bg-white flex align-center justify-center padding' style="width: 100%;" @tap='saveImage_try'>
				<view class="cuIcon-down text-xl text-fw600 margin-right-sm text-333"></view>
				<view class="text-333 text-fw600">保存至手机</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// bgImageUrl: 'https://upload.chinalianjiu.com/productImagesother/C8CA9191D3BB4B1D8A6A592E59FE6FBB.png',
				bgImageUrl: uni.getStorageSync('sharePoster').share_image,
				qrCodeUrl: "",	
				imagePath_bg: undefined,       //wx.getImageInfo转化的图片地址；cavas不能直接用网络地址。
				imagePath_qrcode: undefined,    ////wx.getImageInfo转化的图片地址 ;网络动态请求，小程序码网络图片
				tempSavedImageURL: '',  //cavas绘制图片临时保存路径
				//注意，背景图片时固定大小600x1067，所以canvasStyle宽高比例必须也一致！否则画出来的图片会有多余的一片空白。
				canvasStyle: 'width: 600px;height:1067px;position: fixed;top: -10000px;',    
			};
		},
		onLoad: function (options) {
		    this.ctx = wx.createCanvasContext('myCanvas', this);
		//创建ctx耗时较长，延时500毫秒再请求url
		    setTimeout(res => {
		      this.requestMyIQRCodeUrl()
		    }, 500)
		 },
		methods:{
			requestMyIQRCodeUrl: function() {
			    let that = this
			    that.qrCodeUrl = uni.getStorageSync('sharePoster').miniQrcode;
			    that.draw_try()
			},
			draw_try: function (e) {
			    let urlStr = this.qrCodeUrl;
			    if (urlStr == '' || urlStr == undefined) {
			      return;
			    }
			    let that = this;
			    // 背景图片
			    wx.getImageInfo({
			      src: that.bgImageUrl,
			      success: function (sres) {
			        that.imagePath_bg = sres.path;
			        that.drawCanvasCxt_try()
			      },
			      fail: function (err) {
			      },
			    })
			    // 小程序码图片
			    wx.getImageInfo({
			      src: urlStr,
			      success: function (sres) {
			        that.imagePath_qrcode = sres.path;
			        that.drawCanvasCxt_try()
			      },
			      fail: function (err) {
			      },
			    })
			  },
			
			  drawCanvasCxt_try: function () {
			 //异步调2次此方法；需获取到2张图片特殊路径canvas才能开始绘图
			    if (this.imagePath_bg != undefined && this.imagePath_qrcode != undefined) {
			      this.drawCanvasCxt(this.imagePath_bg, this.imagePath_qrcode)
			    }
			  },
			drawCanvasCxt: function (imagePath_bg, imagePath_qrcode) {
			
			   const res = wx.getSystemInfoSync();
			    const platform = res.platform;
			    let time = 0;
			    if (platform === 'android') {
			      // 在安卓平台，经测试发现如果海报过于复杂在转换时需要做延时，要不然样式会错乱
			      time = 300;
			    }
			//绘制背景图片，大小跟cavas一致。单位是px。如果是本地图片，不要搞太高清，毕竟小程序限制打包后<2M。
			    this.ctx.drawImage(imagePath_bg, 0, 0, 600, 1067)
			//算出小程序码相对于背景海报的坐标。可以写个大概再根据效果慢慢调整
			    this.ctx.drawImage(imagePath_qrcode, 250, 1067-180, 100, 100)
			
			    let that = this;
			//开始渲染
			    this.ctx.draw(false, () => {
			      setTimeout(() => {
			        wx.canvasToTempFilePath({
			          canvasId: 'myCanvas',
			          success: function (res) {
			            let url = res.tempFilePath 
			            console.log('url=' + url)
			            that.tempSavedImageURL = url    // 返回的图片地址保存到一个全局变量里
			          },
			          fail: function (失败) {
			          },
			          complete: function () {
			          }
			        });
			      }, time);
			    });
			  },  
			 saveImage_try: function () {
			     let urlStr = this.tempSavedImageURL;
			     if (urlStr == '' || urlStr == undefined) {
			         return;
			     }
			     
			     let that = this;
			     wx.getSetting({
			       success(res) {
			         if (!res.authSetting['scope.writePhotosAlbum']) {
			           wx.authorize({
			             scope: 'scope.writePhotosAlbum',
			             success() {
			               that.saveImage_do();
			             },
			             fail(err) {
			               //用户拒绝了授权，无法弹出，
			               wx.navigateTo({
			                 url: './instrument/instrumentPage',  //授权说明，提示页面。让用户去授权。
			               })
			             }
			           })
			         }else {
			           that.saveImage_do();
			         }
			       }
			     })
			   },
			 
			   saveImage_do: function (e) {
			     let urlStr = this.tempSavedImageURL;
			     if (urlStr == '' || urlStr == undefined) {
			       return;
			     }
			     wx.saveImageToPhotosAlbum({
			       filePath: urlStr,
			       success: function (fres) {
			 
			       },
			       fail: function (err) {
			       },
			     })
			   }, 
		}
	}
</script>

<style lang="scss">
.whiteContent{
	width: 80%;
	height: 80%;
	margin: 0 auto;
}
</style>
